#include "dialog.h"
#include "ui_dialog.h"


#include <QAction>
#include <QFrame>
#include <QLabel>
#include <QLineEdit>
#include <QDebug>
#include <QPropertyAnimation>
#include <QPushButton>
#include <QMouseEvent>
#include <QMessageBox>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonArray>
#include <QUrlQuery>
#include <QSqlQuery>
#include <QCompleter>
#include <QStringListModel>
#include <QRandomGenerator>
#include <QTimer>
#include <QGraphicsDropShadowEffect>
#include "zsmtp.h"
#include "HttpRequest.h"
#include "emaildialog.h"


QStringList Dialog::getLoginUserInfo() const
{
    return loginUserInfo;
}

void Dialog::setLoginUserInfo(const QStringList &value)
{
    loginUserInfo = value;
}

Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Dialog)
{
    ui->setupUi(this);

    //widget_frame_Init();

    //login_query = new QSqlQuery();

    // 初始化
    login_Init();// 登录

    sigenup_Init();// 注册

    email_Init();// 邮箱验证

    email_lienEdit_Completer();// 邮箱后缀

    // 隐藏主窗体边框
    this->setWindowFlag(Qt::FramelessWindowHint);
    this->setAttribute(Qt::WA_TranslucentBackground);

    // 鼠标拖动窗体
    m_areaMovable = geometry();
    m_bPressed = false;

    // 窗体置于底层
    ui->frame_3->lower();// 注册
    ui->frame_4->lower();// 邮箱验证

    m_http = new HttpRequest(this, "http", "192.168.101.46", "5000");


}



Dialog::~Dialog()
{
    delete ui;
}

void Dialog::login_Init()
{
    // 用户输入框
    QAction *searchAction_YongHuMing = new QAction(ui->LineEdit_login_user);
    searchAction_YongHuMing->setIcon(QIcon("D:\\QT\\qt\\ZhiNengJiaoShuiSystem\\shixun\\shixun\\ZiNengJiaoShui\\image\\not_login.png"));
    ui->LineEdit_login_user->addAction(searchAction_YongHuMing, QLineEdit::LeadingPosition);
    ui->LineEdit_login_user->setPlaceholderText("用户名:");
    ui->LineEdit_login_user->setClearButtonEnabled(true);
    ui->LineEdit_login_user->setMaxLength(20);
    //ui->lineEdit_YongHuMing

    // 密码输入框
    QAction *searchAction_MiMa = new QAction(ui->LineEdit_login_password);
    searchAction_MiMa->setIcon(QIcon("D:\\QT\\qt\\ZhiNengJiaoShuiSystem\\shixun\\shixun\\ZiNengJiaoShui\\image\\password.png"));
    ui->LineEdit_login_password->addAction(searchAction_MiMa, QLineEdit::LeadingPosition);
    ui->LineEdit_login_password->setPlaceholderText("密码:");
    ui->LineEdit_login_password->setEchoMode(QLineEdit::Password);
    ui->LineEdit_login_password->setClearButtonEnabled(true);
    ui->LineEdit_login_password->setMaxLength(20);

    // 设置密码输入框是否显示明文
    ui->LineEdit_login_password->setEchoMode(QLineEdit::Password);


    // 清空提示
    ui->Label_login_user_hint->clear();
    ui->Label_login_password_hint->clear();



    /* 登录界面 信号槽 */
    //选中用户输入框，提示清除
    connect(ui->LineEdit_login_user, &QLineEdit::cursorPositionChanged, [&](){
        if(ui->Label_login_user_hint->text() == "用户不存在!")
            ui->LineEdit_login_user->clear();
        ui->Label_login_user_hint->clear();

    });
    //选中密码输入框，提示清除
    connect(ui->LineEdit_login_password, &QLineEdit::cursorPositionChanged, [&](){
        if(ui->Label_login_password_hint->text() == "密码错误!")
            ui->LineEdit_login_password->clear();
        ui->Label_login_password_hint->clear();
    });

    connect(ui->LineEdit_sigenup_email, &QLineEdit::cursorPositionChanged, [=](){
        if(!ui->Label_sigenup_email_hint->text().isEmpty())
            ui->Label_sigenup_email_hint->clear();
    });

    // 退出
    connect(ui->pushButton_login_exit, &QPushButton::clicked, [&](){
        if(QMessageBox::Yes == QMessageBox::question(nullptr, "提示",tr("确定要关闭吗？"),QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes))
        {
            qDebug() << "系统已退出";
            this->close();
        }
    });

    // 忘记密码跳转email验证界面
    connect(ui->Label_forget, &TMyLabel::Clicked, this, &Dialog::do_Label_longin_forget_clicked);

    //设置具体阴影
    QGraphicsDropShadowEffect *shadow_effect = new QGraphicsDropShadowEffect(this);
    shadow_effect->setOffset(0, 0);
    //阴影颜色
    shadow_effect->setColor(QColor(38, 78, 119, 127));
    //阴影半径
    shadow_effect->setBlurRadius(32);
    ui->frame->setGraphicsEffect(shadow_effect);


    //设置具体阴影
    QGraphicsDropShadowEffect *shadow_effect_2 = new QGraphicsDropShadowEffect(this);
    shadow_effect_2->setOffset(0, 0);
    //阴影颜色
    shadow_effect_2->setColor(QColor(255, 255, 255, 127));
    //阴影半径
    shadow_effect_2->setBlurRadius(32);
    ui->Label_login_background_color->setGraphicsEffect(shadow_effect_2);
}

void Dialog::sigenup_Init()
{
    // 注册用户输入框
    QAction *searchAction_sigenup_user = new QAction(ui->LineEdit_sigenup_user);
    searchAction_sigenup_user->setIcon(QIcon(R"(E:\graduation_project\resource\image\icon\sigen_up.png)"));
    ui->LineEdit_sigenup_user->addAction(searchAction_sigenup_user, QLineEdit::LeadingPosition);
    ui->LineEdit_sigenup_user->setPlaceholderText("用户名:");
    ui->LineEdit_sigenup_user->setClearButtonEnabled(true);
    ui->LineEdit_sigenup_user->setMaxLength(20);


    // 注册用户密码输入框
    QAction *searchAction_sigenup_pwd = new QAction(ui->LineEdit_sigenup_password);
    searchAction_sigenup_pwd->setIcon(QIcon(R"(E:\graduation_project\resource\image\icon\sigen_up_password.png)"));
    ui->LineEdit_sigenup_password->addAction(searchAction_sigenup_pwd, QLineEdit::LeadingPosition);
    ui->LineEdit_sigenup_password->setPlaceholderText("密码:");
    ui->LineEdit_sigenup_password->setEchoMode(QLineEdit::Password);
    ui->LineEdit_sigenup_password->setClearButtonEnabled(true);
    ui->LineEdit_sigenup_password->setMaxLength(20);


    // 注册用户确认密码输入框
    QAction *searchAction_sigenup_pwd_confrim = new QAction(ui->LineEdit_sigenup_password_confirm);
    searchAction_sigenup_pwd_confrim->setIcon(QIcon(R"(E:\graduation_project\resource\image\icon\sigen_up_pwd.png)"));
    ui->LineEdit_sigenup_password_confirm->addAction(searchAction_sigenup_pwd_confrim, QLineEdit::LeadingPosition);
    ui->LineEdit_sigenup_password_confirm->setPlaceholderText("确认密码:");
    ui->LineEdit_sigenup_password_confirm->setEchoMode(QLineEdit::Password);
    ui->LineEdit_sigenup_password_confirm->setClearButtonEnabled(true);
    ui->LineEdit_sigenup_password_confirm->setMaxLength(20);

    // sigenup_email输入框
    QAction *searchAction_login_Email = new QAction(ui->LineEdit_sigenup_email);
    searchAction_login_Email->setIcon(QIcon(R"(E:\graduation_project\resource\image\icon\email.png)"));
    ui->LineEdit_sigenup_email->addAction(searchAction_login_Email, QLineEdit::LeadingPosition);
    ui->LineEdit_sigenup_email->setClearButtonEnabled(true);
    ui->LineEdit_sigenup_email->setPlaceholderText("邮箱:");

    // 设置密码输入框是否显示明文
    ui->LineEdit_sigenup_password->setEchoMode(QLineEdit::Password);

    // 清空提示
    ui->Label_sigenup_email_hint->clear();
    ui->Label_sigenup_user_hint->clear();
    ui->Label_sigenup_password_hint->clear();
    ui->Label_sigenup_password_confirm_hint->clear();


    /* 注册界面 信号槽*/
    //选中用户输入框，提示清除
    connect(ui->LineEdit_sigenup_user, &QLineEdit::cursorPositionChanged, [=](){
        if(ui->Label_sigenup_user_hint->text() == "用户不存在!")
            ui->LineEdit_sigenup_user->clear();
        ui->Label_sigenup_user_hint->clear();

    });
    //选中密码输入框，提示清除
    connect(ui->LineEdit_sigenup_password, &QLineEdit::cursorPositionChanged, [=](){

        if(ui->Label_sigenup_password_hint->text() == "密码错误!")
            ui->LineEdit_sigenup_password->clear();

        ui->Label_sigenup_password_hint->clear();
    });

    // 确认密码输入框
    connect(ui->LineEdit_sigenup_password_confirm, &QLineEdit::cursorPositionChanged, [=](){
        if(ui->Label_sigenup_password_hint->text() == "密码不一致，请重新输入！")
        {
            ui->LineEdit_sigenup_password->clear();
            ui->LineEdit_sigenup_password_confirm->clear();
        }
        //        if(ui->Label_sigenup_password_hint->text() == "注册失败")
        //        {
        //            ui->LineEdit_sigenup_user->clear();
        //            ui->LineEdit_sigenup_password->clear();
        //            ui->LineEdit_sigenup_password_confirm->clear();
        //        }

        ui->Label_sigenup_password_confirm_hint->clear();
    });


    //设置具体阴影
    QGraphicsDropShadowEffect *shadow_effect = new QGraphicsDropShadowEffect(this);
    shadow_effect->setOffset(0, 0);
    //阴影颜色
    shadow_effect->setColor(QColor(0, 0, 255, 127));
    //阴影半径
    shadow_effect->setBlurRadius(22);
    ui->frame_3->setGraphicsEffect(shadow_effect);
}

void Dialog::email_Init()
{
    // email输入框
    QAction *searchAction_Email = new QAction(ui->LineEdit_email);
    searchAction_Email->setIcon(QIcon(R"(E:\graduation_project\resource\image\icon\email.png)"));
    ui->LineEdit_email->addAction(searchAction_Email, QLineEdit::LeadingPosition);
    ui->LineEdit_email->setClearButtonEnabled(true);
    ui->LineEdit_email->setPlaceholderText("邮箱:");

    // email验证码
    QAction *searchAction_verCode = new QAction(ui->LineEdit_verCode);
    searchAction_verCode->setIcon(QIcon(R"(E:\graduation_project\resource\image\icon\vertCode.png)"));
    ui->LineEdit_verCode->addAction(searchAction_verCode, QLineEdit::LeadingPosition);
    ui->LineEdit_verCode->setClearButtonEnabled(true);
    ui->LineEdit_verCode->setPlaceholderText("验证码:");
    // 清空提示
    ui->Label_email_hint->clear();
    ui->Label_verCode_hint->clear();


    /* email验证界面 信号槽 */

    connect(ui->LineEdit_email, &QLineEdit::cursorPositionChanged, [=](){
        if(!ui->Label_email_hint->text().isEmpty())
            ui->Label_email_hint->clear();

    });

    connect(ui->LineEdit_verCode, &QLineEdit::cursorPositionChanged, [=](){
        if(!ui->Label_verCode_hint->text().isEmpty())
            ui->Label_verCode_hint->clear();
    });

    //设置具体阴影
    QGraphicsDropShadowEffect *shadow_effect = new QGraphicsDropShadowEffect(this);
    shadow_effect->setOffset(0, 0);
    //阴影颜色
    shadow_effect->setColor(QColor(0, 0, 255, 127));
    //阴影半径
    shadow_effect->setBlurRadius(22);
    ui->frame_4->setGraphicsEffect(shadow_effect);
}

// 邮箱后缀下拉框提示
void Dialog::email_lienEdit_Completer()
{
    // 创建QLineEdit和QCompleter对象
    m_completer_email = new QCompleter(this);
    m_model_email     = new QStringListModel(this);

    // 设置QCompleter的自动补全模式为PopupCompletion
    m_completer_email->setCaseSensitivity(Qt::CaseInsensitive);
    m_completer_email->setCompletionMode(QCompleter::PopupCompletion);

    // 将QCompleter与QLineEdit关联
    ui->LineEdit_email->setCompleter(m_completer_email);

    ui->LineEdit_sigenup_email->setCompleter(m_completer_email);

//    ui->LineEdit_email->setStyleSheet("QCompleter { "
//                                      "border: 1px solid gray; "
//                                      "border-radius: 5px; "
//                                      "padding: 0 8px; "
//                                      "background-color: blue; "
//                                      "selection-background-color: blue; "
//                                      "}");


    // 将自定义的数据模型设置给QCompleter
    m_completer_email->setModel(m_model_email);

    // 在这里添加常用的邮箱后缀
    m_emailSuffixes << "@qq.com"
                  << "@163.com"
                  << "@126.com"
                  << "@139.com"
                  << "@gmail.com"
                  << "@outlook.com";  // 添加更多的邮箱后缀

    // 设置model的数据
    m_model_email->setStringList(m_emailSuffixes);

    connect(ui->LineEdit_email, &QLineEdit::textChanged, this, QOverload<const QString&>::of(&Dialog::do_mailbox_suffix));// 输入框绑定，邮箱验证界面
    connect(ui->LineEdit_sigenup_email, &QLineEdit::textChanged, this, QOverload<const QString&>::of(&Dialog::do_mailbox_suffix));// 输入框绑定，注册界面

    // 点击选项后清除输入框中的内容
    connect(m_completer_email, QOverload<const QString&>::of(&QCompleter::activated), [=](){
        if(!ui->LineEdit_email->text().isEmpty())
        {
            ui->LineEdit_email->text().clear();
        }
    });

    // 点击选项后清除输入框中的内容
    connect(m_completer_email, QOverload<const QString&>::of(&QCompleter::activated), [=](){
        if(!ui->LineEdit_sigenup_email->text().isEmpty())
        {
            ui->LineEdit_sigenup_email->text().clear();
        }
    });
}


// 鼠标点击事件
void Dialog::mousePressEvent(QMouseEvent *e)
{
    //鼠标左键
    if(e->button() == Qt::LeftButton)
    {
        m_ptPress = e->pos();
//        qDebug() << pos() << ui->Label_forget->pos() << e->pos() << m_ptPress;
        m_bPressed = m_areaMovable.contains(m_ptPress);

    }
    // 获取窗体在指定父类窗体中的坐标
    QPoint pos = ui->Label_forget->mapTo(this, QPoint(0, 0));

    if (e->button() == Qt::LeftButton && (e->pos().x() >= pos.x()
                                          && e->pos().x() <= pos.x() + ui->Label_forget->width()
                                          && e->pos().y() >= pos.y()
                                          && e->pos().y() <= pos.y() + ui->Label_forget->height())) {
        qDebug() << "Label Clicked!";

        qDebug() << e->pos() << ui->Label_forget->pos() << pos;

        // 发送email界面移动信号
        emit this->forget_clicked();
    }

}

// 鼠标移动事件
void Dialog::mouseMoveEvent(QMouseEvent *e)
{
    if(m_bPressed)
    {
//        qDebug() << pos() << e->pos() << m_ptPress;
        move(pos() + e->pos() - m_ptPress);
    }
}

// 鼠标松手事件
void Dialog::mouseReleaseEvent(QMouseEvent *)
{
    m_bPressed = false;
}

//设置鼠标按下的区域
void Dialog::setAreaMovable(const QRect rt)
{

    if(m_areaMovable != rt)
    {
        m_areaMovable = rt;
    }
}


// 解析Json
int Dialog::getJsonDatas(QJsonObject obj)
{
    int json_flag = 0;
    QString codeStr;

    // 打印输出整个Json串
    qDebug() << "rootObj:" << obj;

    // "code"
    if(obj.value("code").isDouble())
    {
        codeStr = QString::number(obj.value("code").toDouble());
    }
    else if(obj.value("code").isString())
    {
        codeStr = obj.value("code").toString();
    } else {
        json_flag = 1;
    }

    qDebug() << "code:" << codeStr;

    // "data[]"
    QJsonArray dataArray = obj.value("data").toArray();

    qDebug() << QString("data[] size = %1").arg(dataArray.size());

    // 检查数组是否有元素
    if(!dataArray.isEmpty())
    {
        // 遍历数组
        for(const QJsonValue &value : dataArray)
        {
            if(value.isObject())
            {
                // 将数组元素转换为对象
                QJsonObject itemObj = value.toObject();

                // 获取data数据
                int id = itemObj.value("id").toInt();
                QString username = itemObj.value("username").toString();
                QString password = itemObj.value("password").toString();

                m_login_user_list.append(username);

                m_username = username;
                m_password = password;

                qDebug() << "id:" << id;
                qDebug() << "username:" << username;
                qDebug() << "password:" << password;
            }
        }
    } else {
        json_flag = 2;
    }

    // "message"
    QString message = obj.value("message").toString();
    qDebug() << "message:" << message;

    return json_flag;
}


// 检查用户输入信息是否正确
void Dialog::info_check(QString operate, QLineEdit *lineEdit_user, QLineEdit *lineEdit_pwd, QLabel *label_user_hint, QLabel *label_pwd_hint)
{
    bool user_flag = false;
    bool pwd_flag = false;

    QString name = lineEdit_user->text();
    QString pwd = lineEdit_pwd->text();

    qDebug() << "HTTP user: " << name << m_username;

    if(m_username != name)
    {
        if(m_message == "user exists")
        {
            label_user_hint->setText(tr("用户已注册"));
        }
        else if(m_message == "user not exists")
        {
            //            QMessageBox::warning(nullptr, "错误提示","用户不存在，请先注册新用户！", QMessageBox::Ok, QMessageBox::Ok);
            label_user_hint->setText(tr("用户不存在"));
        }
    }
    else if(operate == "登录")
    {
        user_flag = true;
    }
    else if(operate == "注册")
    {
        label_user_hint->setText(tr("用户已注册"));

        qDebug() << "用户已注册.";
        user_flag = true;
    }

    qDebug() << QString("HTTP %1 password: ").arg(operate)  << pwd << m_password;
    if(user_flag && (m_password) == pwd)
    {
        pwd_flag = true;
        qDebug() << "密码正确.";
    } else {

        if(m_code != 300)
            label_pwd_hint->setText(tr("用户名或密码错误!"));
    }

    if(user_flag && pwd_flag)
    {
        qDebug() << "用户: " << name << QString("%1成功!").arg(operate);
    } else {
        qDebug() << "用户: " << name <<  QString("%1失败!").arg(operate);
    }

    // 用完后，清除HTTP获取到的用户数据
    m_username.clear();
    m_password.clear();

}





// 导入所有用户到提示框
void Dialog::getAllUsers()
{

    NormalGetRequest("/login/users","","");

    QCompleter *completer = new QCompleter(m_login_user_list, ui->LineEdit_login_user);   //创建QCompleter对象
    completer->setMaxVisibleItems(5);   // 设置最大显示
    //    completer->setCompletionMode(QCompleter::InlineCompletion);   // 在光标后面补全
    completer->setFilterMode(Qt::MatchContains);      // 设置自动补全匹配模式
    ui->LineEdit_login_user->setCompleter(completer); //设置自动补全


    qDebug() << "已记录" << m_login_user_list.size() << "个账号信息";
}


// 邮箱格式，正则表达式检测
bool Dialog::CheckEmailFormat(QString email)
{
    QRegExp re("^[A-Za-z0-9]+([_\\.][A-Za-z0-9]+)*@([A-Za-z0-9\\-]+\\.)+[A-Za-z]{2,6}$");

    return re.exactMatch(email);
}


// 生成请求
QNetworkRequest Dialog::setGetRequest(QString path, QString paramer1 = "", QString paramer2 = "",  QString scheme = "http", QString serverAddr = "127.0.0.1", QString port = "5000")
{
    // 生成对应网络请求
    QNetworkRequest request;
    QString requestHeader = scheme + "://" + serverAddr + ":" + port;
    QString Path;

    if(paramer1.isEmpty() && paramer1.isEmpty())
    {
        Path = QString("%1").arg(path);
    } else {
        Path = QString("%1?username=%2&password=%3").arg(path).arg(paramer1).arg(paramer2);
    }

    QString fullRequest = requestHeader + Path;

    request.setUrl(QUrl(fullRequest));
    return request;
}


// 发送GET请求
int Dialog::NormalGetRequest(QString  path, QString username, QString password)
{
    // 生成对应网络请求
    QNetworkRequest request(setGetRequest(path, username, password));

//    QNetworkRequest request;
//    request.setUrl(QUrl("http://127.0.0.1:5000/login?username=lfy&password=123"));
    //request.setUrl(QUrl("http://192.168.254.130:5000/login_users"));

    //发送Get请求
    QNetworkAccessManager manager;
    QNetworkReply *reply = manager.get(request);
    QEventLoop eventLoop;
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec(QEventLoop::ExcludeUserInputEvents);

    //对请求的返回异常进行处理
    if(reply->error() != QNetworkReply::NoError)
    {
        QString error = reply->errorString();
        qDebug() << "Reply Error:" << error;
        return reply->error();
    }

    //解析返回的Json
    QByteArray replyData = reply->readAll();
    QJsonParseError json_error;

    //
    QJsonDocument jsonDoc(QJsonDocument::fromJson(replyData, &json_error));
    if(json_error.error != QJsonParseError::NoError)
    {
        return -1;
    }

    // Json对象
    QJsonObject rootObj = jsonDoc.object();
    int tmp;
    m_code = rootObj.value("code").toDouble();
    m_message = rootObj.value("message").toString();

    if(m_code == 200)
    {
        qDebug() << "HTTP 成功";

        // 返回代码为200的时候证明请求成功对包含的结构数据进行处理
        if(rootObj.contains("data"))
        {
            qDebug() << "包含data";
            // 对JSON进行解析
            tmp = getJsonDatas(rootObj);
        }
        return 0;
    } else {
        qDebug() << "HTTP 失败";
        //请求失败对应的处理
        return rootObj.value("code").toDouble();
    }

    qDebug() << "GET Json结果：" << tmp;
    return tmp;
}


// 发送POST请求
int Dialog::NormalPostRequest(QString  path, QString username, QString password)
{
    //生成对应的网址请求
    QNetworkRequest request = setGetRequest(path,"","");
    //request.setUrl(QUrl("http://192.168.254.130:5000/login"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    // 构建POST数据
    QUrlQuery postData;
    postData.addQueryItem("user_name", username.toUtf8());
    postData.addQueryItem("user_password", password.toUtf8());

    //发送请求
    QNetworkAccessManager manager;
    //    QNetworkReply *reply = manager.post(request, data);
    QNetworkReply *reply = manager.post(request, postData.toString(QUrl::FullyEncoded).toUtf8());
    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()),&eventLoop, SLOT(quit()));
    eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
    if(reply->error() != QNetworkReply::NoError)
    {
        return reply->error();
    }

    //解析返回的Json结果
    QByteArray replyData = reply->readAll();
    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(replyData, &json_error));
    if(json_error.error != QJsonParseError::NoError)
    {
        return -1;
    }

    // Json对象
    QJsonObject rootObj = jsonDoc.object();
    int tmp;

    m_code = rootObj.value("code").toDouble();
    m_message = rootObj.value("message").toString();

    if(m_code == 200)
    {
        qDebug() << "HTTP 成功";

        // 返回代码为200的时候证明请求成功对包含的结构数据进行处理
        if(rootObj.contains("data"))
        {
            qDebug() << "包含data";
            // 对JSON进行解析
            tmp = getJsonDatas(rootObj);
        }
        return 0;
    } else {
        qDebug() << "HTTP 失败";
        //请求失败对应的处理
        return rootObj.value("code").toDouble();
    }

    qDebug() << "POST Json结果：" << tmp;
    return tmp;
}

// 注册POST请求
int Dialog::NormalPostRequest(QString  path, QString username, QString password, QString email, QString home = "ROOT")
{
    //生成对应的网址请求
    QNetworkRequest request = setGetRequest(path,"","");
    //request.setUrl(QUrl("http://192.168.254.130:5000/login"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");


    // 构建POST数据
    QUrlQuery postData;
    postData.addQueryItem("user_name", username.toUtf8());
    postData.addQueryItem("user_password", password.toUtf8());
    postData.addQueryItem("user_email", email.toUtf8());
    postData.addQueryItem("user_home", home.toUtf8());

    //发送请求
    QNetworkAccessManager manager;
    //    QNetworkReply *reply = manager.post(request, data);
    QNetworkReply *reply = manager.post(request, postData.toString(QUrl::FullyEncoded).toUtf8());
    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()),&eventLoop, SLOT(quit()));
    eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
    if(reply->error() != QNetworkReply::NoError)
    {
        return reply->error();
    }

    //解析返回的Json结果
    QByteArray replyData = reply->readAll();
    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(replyData, &json_error));
    if(json_error.error != QJsonParseError::NoError)
    {
        return -1;
    }

    // Json对象
    QJsonObject rootObj = jsonDoc.object();
    int tmp;

    m_code = rootObj.value("code").toDouble();
    m_message = rootObj.value("message").toString();

    if(m_code == 200)
    {
        qDebug() << "HTTP 成功";

        // 返回代码为200的时候证明请求成功对包含的结构数据进行处理
        if(rootObj.contains("data"))
        {
            qDebug() << "包含data";
            // 对JSON进行解析
            tmp = getJsonDatas(rootObj);
        }
        return 0;
    } else {
        qDebug() << "HTTP 失败";
        //请求失败对应的处理
        return rootObj.value("code").toDouble();
    }

    qDebug() << "POST Json结果：" << tmp;
    return tmp;
}



// 注册界面移动动画
void Dialog::on_pushButton_login_sigenup_clicked()
{
    QPropertyAnimation *animation = new QPropertyAnimation(ui->frame_3, "geometry");

    static bool frame_flag = false;

    int start_x = ui->frame->x()+90;
    int start_y = ui->frame->y()+70;

    int w = ui->frame_3->width();
    int h = ui->frame_3->height();


    if(frame_flag)
    {
        // 清空输入框
        ui->LineEdit_sigenup_user->clear();
        ui->LineEdit_sigenup_password->clear();
        ui->LineEdit_sigenup_password_confirm->clear();
        ui->Label_sigenup_user_hint->clear();
        ui->Label_sigenup_user_hint->clear();
        ui->LineEdit_sigenup_password_confirm->clear();

        animation->setStartValue(QRect(start_x,start_y,w,h));
        animation->setEndValue(QRect(start_x+w,start_y,w,h));
    } else {

        animation->setStartValue(QRect(start_x+w,start_y,w,h));
        animation->setEndValue(QRect(start_x,start_y,w,h));
    }

    animation->setDuration(500);
    animation->start();

    frame_flag = !frame_flag;
}


// email界面移动动画
void Dialog::do_Label_longin_forget_clicked()
{
    QPropertyAnimation *animation = new QPropertyAnimation(ui->frame_4, "geometry");

    static bool frame_flag = false;

    int start_x = ui->frame->x();
    int start_y = ui->frame->y()+70;

    int w = ui->frame_4->width();
    int h = ui->frame_4->height();


    if(frame_flag)
    {
        // 清空输入框
        ui->LineEdit_email->clear();
        ui->LineEdit_verCode->clear();
        ui->Label_email_hint->clear();
        ui->Label_verCode_hint->clear();

        animation->setStartValue(QRect(start_x,start_y,w,h));
        animation->setEndValue(QRect(start_x-w,start_y,w,h));
    } else {

        animation->setStartValue(QRect(start_x-w,start_y,w,h));
        animation->setEndValue(QRect(start_x,start_y,w,h));
    }

    animation->setDuration(500);
    animation->start();

    frame_flag = !frame_flag;
}



// 登录
void Dialog::on_pushButton_login_enter_clicked()
{
    //    NormalGetRequest("lfy","123456");

    QString name = ui->LineEdit_login_user->text().trimmed();
    QString pwd = ui->LineEdit_login_password->text().trimmed();


    // 是否输入用户名
    if(name.isEmpty())
    {
        //            QMessageBox::information(nullptr, "错误提示","请输入用户名！", QMessageBox::Ok, QMessageBox::Ok);
        ui->Label_login_user_hint->setText("请输入用户名！");
        qDebug() << "未输入用户名...";
        return;
    }
    // 是否输入密码
    if(pwd.isEmpty())
    {
        //            QMessageBox::information(nullptr, "错误提示","请输入密码！", QMessageBox::Ok, QMessageBox::Ok);
        ui->Label_login_password_hint->setText("请输入密码！");
        qDebug() << "未输入密码...";
        return;
    }

    QMap<QString, QString> map_get;

    map_get.insert("user_name", name);
    map_get.insert("user_password", pwd);

    // 发送POST请求
    int tmp = m_http->NormalPostRequest("/login", map_get);

//    if(m_code == 200 && m_message == "登录成功")
    if(HttpRequest::m_map_post.value("code").toInt() == 200)
    {
//        QStringList user_list;

//        user_list.append(HttpRequest::m_map_post.value("data").toList().at(0).toString());
//        user_list.append(HttpRequest::m_map_post.value("data").toList().at(1).toString());
//        user_list.append(HttpRequest::m_map_post.value("data").toList().at(2).toString());

//        setLoginUserInfo(user_list);

        emit user_info(name);
        qDebug() << "登录成功，进行主界面";

        this->accept();
    }



//    // 信息比对
//    info_check("登录", ui->LineEdit_login_user, ui->LineEdit_login_password,
//               ui->Label_login_user_hint, ui->Label_login_password_hint);

}

// 注册
void Dialog::on_pushButton_sigenup_clicked()
{
    ui->Label_sigenup_user_hint->clear();
    ui->Label_sigenup_password_hint->clear();
    ui->Label_sigenup_password_confirm_hint->clear();

    QString name = ui->LineEdit_sigenup_user->text().trimmed();
    QString pwd = ui->LineEdit_sigenup_password->text().trimmed();;
    QString pwd_confirm = ui->LineEdit_sigenup_password_confirm->text().trimmed();
    QString email = ui->LineEdit_sigenup_email->text().trimmed();


    // 是否输入用户名
    if(name.isEmpty())
    {
        //            QMessageBox::information(nullptr, "错误提示","请输入用户名！", QMessageBox::Ok, QMessageBox::Ok);
        ui->Label_sigenup_user_hint->setText("请输入用户名！");
        qDebug() << "未输入用户名...";
        return;
    }
    // 是否输入密码
    if(pwd.isEmpty())
    {
        //            QMessageBox::information(nullptr, "错误提示","请输入密码！", QMessageBox::Ok, QMessageBox::Ok);
        ui->Label_sigenup_password_hint->setText("请输入密码！");
        qDebug() << "未输入密码...";
        return;
    }

    // 确认密码
    if(pwd_confirm.isEmpty())
    {
        ui->Label_sigenup_password_confirm_hint->setText("请输入密码！");
        qDebug() << "未输入密码...";
        return;
    }

    if(email.isEmpty())
    {
        ui->Label_sigenup_email_hint->setText("请输入邮箱地址！");
        qDebug() << "未输入邮箱地址...";
        return;
    }

    if(CheckEmailFormat(email) == false)
    {
        ui->Label_sigenup_email_hint->setText("邮箱格式不正确,请重新输入");
        qDebug() << "邮箱格式不正确...";
        return;
    }

    // 密码是否一致
    if(pwd != pwd_confirm)
    {
        ui->Label_sigenup_password_confirm_hint->setText("密码不一致，请重新输入！");
        qDebug() << "密码不一致...";
        return;
    }

    EmailDialog *edlg = new EmailDialog(nullptr, email);

    if(edlg->exec() != EmailDialog::Accepted)
    {
        return;
    }

    QMap<QString, QString> map_post;

    map_post.insert("user_name", name);
    map_post.insert("user_password", pwd);
    map_post.insert("user_email", email);
    map_post.insert("user_home", "ELIZA");

    // 发送POST请求
    int tmp = m_http->NormalPostRequest("/register", map_post);

    if(200 == HttpRequest::m_map_post.value("code").toInt())
    {
        ui->Label_sigenup_password_confirm_hint->setText("注册成功");
        qDebug() << "m_map_post 注册成功";
        // 注册界面跳转
        emit ui->pushButton_login_sigenup->clicked();
    }


//    // 信息比对
//    info_check("注册", ui->LineEdit_sigenup_user, ui->LineEdit_sigenup_password,
//               ui->Label_sigenup_user_hint, ui->Label_sigenup_password_hint);

    if(tmp)
    {
        qDebug() << "POST:失败" << tmp;

        ui->Label_sigenup_password_confirm_hint->setText("注册失败");
        qDebug() << "注册失败";
    } else {
        qDebug() << "POST:成功" << tmp;

        ui->Label_sigenup_password_confirm_hint->setText("注册成功");
        qDebug() << "注册成功";

        // 注册界面跳转
        //emit ui->pushButton_login_sigenup->clicked();
    }

}

// email发送验证码
void Dialog::on_pushButton_email_clicked()
{
    QString recvaddr0 = ui->LineEdit_email->text();
    // 判断逻辑

    if(recvaddr0.isEmpty())
    {
        ui->Label_email_hint->setText("请输入邮箱地址");
        qDebug() << "未输入邮箱地址";
        return;
    }

    // 邮箱格式是否正确
    if(CheckEmailFormat(recvaddr0)){//验证邮箱格式
        QMessageBox::information(NULL,"提示","验证码将在30s内发送至您的邮箱，请耐心等待。");

        // 输入的时候有邮箱后缀提示
        ZSmtp *smtp = new ZSmtp("smtp.163.com");

        m_randCodeStr = smtp->getRandStr(6);// 生成6位验证码
        connect(smtp, SIGNAL(disconnected()), smtp, SLOT(deleteLater()));
        connect(smtp, &ZSmtp::emailStatus, this, &Dialog::do_sendResult);
        QString subject="智能家居控制系统";
        QString content="邮箱验证登录，本次操作的验证码为：" + m_randCodeStr;
        smtp->sendEmail("13272456305@163.com", "LCAQZWXNGNPHDELL", recvaddr0, subject, content);
        ui->pushButton_email->setEnabled(false);
    }
    else{
        //QMessageBox::warning(NULL,"提示","邮箱格式不正确,请重新输入。");
        ui->Label_email_hint->setText("邮箱格式不正确,请重新输入");
        qDebug() << "邮箱格式不正确...";
    }
}

// 邮箱是否发送成功
void Dialog::do_sendResult(int status)
{
    if(status == EMAIL_SUCCEED)	//邮件发送成功
    {
        //do something
        qDebug() << "邮件发送成功";

    }
    else if(status == EMAIL_ERROR)
    {//邮件发送失败（原因可能是发、收件人邮箱号写错了，smtp服务器崩了等）
        //do something
        qDebug() << "邮件发送失败";

    }
    ui->pushButton_email->setEnabled(true);
}


// 邮箱后缀
void Dialog::do_mailbox_suffix(const QString &text)
{

    QStringList filteredSuggestions;
    QStringList tempSuffix = m_emailSuffixes;

    for(const QString &suffix: tempSuffix)
    {
        filteredSuggestions.append(text + suffix);
    }
    //删除多余@
    for(QString &email: filteredSuggestions)
    {
        if(email.count("@") >= 2)
        {
            int firstIndex = email.indexOf("@"); // 第一个@
            int secondIndex = email.indexOf("@", firstIndex + 1); // 第二个@
            if (secondIndex != -1) {
                email.remove(firstIndex, secondIndex - firstIndex);
            }
        }
    }
    // 更新到模型
    m_model_email->setStringList(filteredSuggestions);
}

// 填写登录信息
void Dialog::do_email_login_user_info(QString name, QString pwd)
{
    ui->LineEdit_login_user->setText(name);
    ui->LineEdit_login_password->setText(pwd);
}

void Dialog::closeEvent(QCloseEvent *event)
{
    QDialog::closeEvent(event);
    emit loginWindowClosed();
}


// 确认验证码
void Dialog::on_pushButton_email_enter_clicked()
{
    //    labelShowCounDown(ui->pushButton_email, 30);

    qDebug() << "email_enter_clicked";

    QString vercode = ui->LineEdit_verCode->text();

    if(vercode.isEmpty())
    {
        qDebug() << "未输入验证码...";
        ui->Label_verCode_hint->setText("请输入验证码");
        return;
    }


    if(vercode == m_randCodeStr)
    {
        qDebug() << "验证码正确!";
        ui->Label_verCode_hint->setText("验证成功");

        QMap<QString, QString> map;

        map.insert("user_email", ui->LineEdit_email->text().trimmed());

        m_http->NormalPostRequest("/user/email", map);

        QString user_name = HttpRequest::m_map_post.value("user_name").toString();
        QString user_email = HttpRequest::m_map_post.value("user_email").toString();
        //获取用户数据
        qDebug() << "用户名" << user_name;
        qDebug() << "邮箱"   << user_email;

        // 用户名密码发送到登录界面输入框
//        QString name, pwd;
//        emit this->email_login_user_info(name, pwd);

        emit user_info(user_name);

        this->do_Label_longin_forget_clicked();
    } else {
        ui->Label_verCode_hint->setText("验证失败");
        qDebug() << "验证码错误!";
    }

}


